<template>
  <div class="flex h-full">
    <f-select-group
      v-model="searchForm.group_id"
      @change="handleGroupChange"
      ref="groupRef"></f-select-group>
    <!-- 列表 -->
    <div class="flex-1 ml-[10px] overflow-hidden">
      <f-table
        ref="tableRef"
        @register="register">
        <template #header-left>
          <el-button
            v-permission:1201="$route.meta.auth"
            type="primary"
            @click="handleAdd"
            >{{ t("add") }}</el-button
          >
          <el-button
            v-permission:1201="$route.meta.auth"
            type="warning"
            @click="handleBatchGroup"
            >{{ t("batchGroup") }}</el-button
          >
          <!-- <el-button
            v-permission:1202="$route.meta.auth"
            @click="handleBatchDelete"
            >{{ t("deleteBatch") }}</el-button
          > -->
        </template>

        <template #action="{ row }">
          <el-space wrap>
            <el-button
              type="primary"
              link
              @click="handleViewDetail(row)"
              >资金明细</el-button
            >
            <el-button
              type="primary"
              link
              @click="handleEdit(row)"
              >{{ t("edit") }}</el-button
            >
            <el-button
              type="primary"
              link
              @click="handleDelete(row)"
              >{{ t("delete") }}</el-button
            >
            <el-dropdown @command="handleCommand($event, row)">
              <el-button
                type="primary"
                text
                >更多</el-button
              >
              <template #dropdown>
                <el-dropdown-menu>
                  <div v-permission:1203="$route.meta.auth">
                    <el-dropdown-item command="1">充值</el-dropdown-item>
                  </div>
                  <div v-permission:1204="$route.meta.auth">
                    <el-dropdown-item command="2">用户转移</el-dropdown-item>
                  </div>
                  <div v-permission:1205="$route.meta.auth">
                    <el-dropdown-item command="3">资产转移</el-dropdown-item>
                  </div>
                  <el-dropdown-item command="4">修改密码</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-space>
        </template>
      </f-table>
    </div>
    <!-- 新建分组弹框 -->
    <f-form-model
      ref="formModelRef"
      :is="formModelName"
      @change="() => methods.reload()"></f-form-model>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { t } from "@/lang";
import FSelectGroup from "@/addon/htscrm/components/f-select-group/index.vue";
import FTable, {
  BasicColumn,
  useTable,
} from "@/addon/htscrm/components/f-table";
import {
  tableColumns,
  tableSearchFormItems,
} from "@/addon/htscrm/data/store.list";
import { batchDeleteStoreApi, getStoreListApi, deleteStoreApi } from "@/addon/htscrm/api";
import { ElMessage, ElMessageBox } from "element-plus";
import FFormModel from "@/addon/htscrm/components/f-form-model";
import { useRouter } from "vue-router";

const formModelRef = ref();
const formModelName = ref("StoreForm");

const router = useRouter();

const searchForm = ref({
  group_id: 0,
});
const tableRef = ref();
const { methods, register } = useTable({
  rowKey: "id",
  searchFromItems: tableSearchFormItems(t),
  columns: tableColumns(t) as BasicColumn<IStoreItem>[],
  beforeFetch: (opt) => {
    return { ...opt, group_id: searchForm.value.group_id || "" };
  },
  api: async (opt) => (await getStoreListApi(opt)).data,
});

/**
 * @description 批量分组
 */
function handleBatchGroup() {
  const selection: IStoreItem[] = methods.getSelectionRows();
  if (selection.length == 0) {
    ElMessage.warning(t("batchGroupStore"));
    return;
  }
  const params = {
    id: selection.map((item) => item.id),
    title: selection.map((item) => item.title),
  }
  formModelName.value = "MultipleEditGroupForm";
  formModelRef.value?.show(t("batchGroup"), params);
}

/**
 * @description 新增
 */
function handleAdd() {
  formModelName.value = "StoreForm";
  formModelRef.value?.show(t("add"), {group_id: searchForm.value.group_id});
}
/**
 * @description 编辑
 */
function handleEdit(row: IStoreItem) {
  formModelName.value = "StoreForm";
  formModelRef.value?.show(t("update"), row);
}

/**
 * @description 删除
 */
async function handleDelete(row: IStoreItem) {
  const action = await ElMessageBox.confirm(t('deleteTips'), t('alert.title'))

    if (action === 'confirm') {
      try {
        await deleteStoreApi(row.id)

        ElMessage.success(t('deleteSuccess'))
        // 重新加载数据
        methods.reload()
      } catch (error) {
        ElMessage.error(error.msg || '删除失败,请重试')
      }
    }
}

/**
 * @description 批量删除数据
 */
async function handleBatchDelete() {
  const selection: IStoreItem[] = methods.getSelectionRows();
  if (selection.length == 0) {
    ElMessage.warning(t("deleteEmptyTips"));
    return;
  }
  const ids = selection.map((item) => item.id);

  const { value, action } = await ElMessageBox.prompt(
    t("deleteBatchTips"),
    t("alert.title"),
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputPlaceholder: "请输入操作密码",
      inputType: "password",
    }
  );
  console.log(action, value);

  if (action === "confirm") {
    await batchDeleteStoreApi(ids);

    ElMessage.success(t("deleteSuccess"));
    // 清空选项
    methods.clearSelection();
    // 重新加载数据
    methods.reload();
  }
}

/**
 * @description 切换分组
 */
function handleGroupChange() {
  methods.reload();
}

function handleViewDetail(row: IStoreItem) {
  router.push({
    path: "/htscrm/store/financial-details",
    query: { id: row.id },
  });
}

function handleCommand(key: string, row: IStoreItem) {
  switch (key) {
    case "1":
      formModelName.value = "StoreEditForm";
      formModelRef.value?.show("充值", row, 1);
      break;
    case "2":
      formModelName.value = "StoreEditForm";
      formModelRef.value?.show("用户转移", row, 2);
      break;
    case "3":
      formModelName.value = "StoreEditForm";
      formModelRef.value?.show("资产转移", row, 3);
      break;
    case "4":
      formModelName.value = "StoreEditForm";
      formModelRef.value?.show("修改密码", row, 4);
      break;
  }
}
</script>

<style lang="scss" scoped></style>
